package cn.edu.bupt.scidata.service.impl;

import cn.edu.bupt.scidata.config.FieldCodeConfig;
import cn.edu.bupt.scidata.config.ResultEnum;
import cn.edu.bupt.scidata.mapper.ProjectsMapper;
import cn.edu.bupt.scidata.model.project.*;
import cn.edu.bupt.scidata.repository.ProjectRepository;
import cn.edu.bupt.scidata.service.ProjectService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("projectService")
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    @Qualifier("projectRepository")
    private ProjectRepository projectRepository;

    @Autowired
    RestHighLevelClient client;

    @Autowired
    private ProjectsMapper projectsMapper;

    @Override
    public Page<ElasticSearchProject> fetchAll(int size, int page, String sort) {
        Pageable pageable;
        if (sort.equals("relevance")) {
            pageable = PageRequest.of(page, size, Sort.Direction.DESC, "_score");
        } else {
            pageable = PageRequest.of(page, size, Sort.Direction.DESC, "deadline");
        }
        return projectRepository.findAll(pageable);
    }

    @Override
    public MySQLProject getByApproval(String approval) {
        MySQLProject project = projectsMapper.getByApproval(approval);
        String key = project.getBranch().length() > 5 ? project.getBranch().substring(0, 5) : project.getBranch();
        String branch = FieldCodeConfig.getMap().get(key);
        project.setBranch(branch);
        return project;
    }

    @Override
    public List<Results> getResultsByApproval(String approval) {
        return projectsMapper.getResultsByApproval(approval);
    }

    @Override
    public List<MySQLProject> getResearcherProjects(String manager, String institute) {
        return projectsMapper.getResearcherProjects(manager, institute);
    }

    @Override
    public Trace traceProjectByApproval(String approval) {
        Trace traces = new Trace();
        List<Node> nodes = new ArrayList<>();
        List<String[]> links = new ArrayList<>();
        //todo:实现真正的追踪

        MySQLProject project = this.getByApproval(approval);
        List<MySQLProject> projects = this.getResearcherProjects(project.getManager(), project.getInstitute());

        int id = 0;
        for (MySQLProject p : projects) {
            int root = id, cur = id;
            List<Results> results = this.getResultsByApproval(approval);
            Node node;
            if (p.getApproval().equals(approval)) {
                node = new Node(String.valueOf(id), p.getTitle(), 0, p.getSummary(), true, 50);
            } else {
                node = new Node(String.valueOf(id), p.getTitle(), 1, p.getSummary(), true, 50);
            }
            id++;
            nodes.add(node);

            for (int j = 0; j < results.size(); j++) {
                if (j == 0 || !results.get(j).getKind().equals(results.get(j - 1).getKind())) {
                    nodes.add(new Node(String.valueOf(id), results.get(j).getKind(), getCate(results.get(j).getKind()), results.get(j).getKind(), false, 30));
                    links.add(new String[]{String.valueOf(root), String.valueOf(id)});

                    cur = id++;
                } else {
                    links.add(new String[]{String.valueOf(cur), String.valueOf(id)});
                    nodes.add(new Node(String.valueOf(id), results.get(j).getTitle(), getCate(results.get(j).getKind()), results.get(j).getKind(), false, 18));
                    id++;
                }
            }
        }

        List<String> tmp = new ArrayList<>();
        for (Node node : nodes) {
            if (node.project) tmp.add(node.getId());
        }
        for (int i = 0; i < tmp.size() - 1; i++) {
            links.add(new String[]{tmp.get(i), tmp.get(i + 1)});
        }

        traces.setNodes(nodes);
        traces.setLinks(links);
        return traces;
    }

    @Override
    public Trend trendProjectByApproval(String approval) {
        List<Results> results = this.getResultsByApproval(approval);
        List<String> x = new ArrayList<>();
        List<String> legend = new ArrayList<>();
        Map<String, int[]> map = new HashMap<>();
        Trend trend = new Trend();

        //确保成果时间合法
        MySQLProject project = this.getByApproval(approval);
        int origin = project.getOrigin() / 100;
        int deadline = project.getDeadline() / 100;
        int start = deadline, end = origin;
        for (Results r : results) {
            int year = r.getTime();
            if (year == -1) year = deadline;
            if (year < origin || year > deadline) continue;
            if (year < start) start = year;
            if (year > end) end = year;
        }

        for (int i = start; i <= end; i++) {
            x.add(String.valueOf(i));
        }

        for (Results r : results) {
            int[] y;
            int year = r.getTime();
            if (year < start || year > end) year = end;
            if (map.containsKey(r.getKind())) {
                y = map.get(r.getKind());
            } else {
                legend.add(r.getKind());
                y = new int[x.size()];
            }
            y[year - start]++;
            map.put(r.getKind(), y);
        }
        trend.setX(x);
        trend.setLegend(legend);
        trend.setTrend(map);
        return trend;
    }

    @Override
    public Page<ElasticSearchProject> search(int size, int page, String keyword, String time, String code, String sort) {
        Pageable pageable;
        if (sort.equals("relevance")) {
            pageable = PageRequest.of(page, size, Sort.Direction.DESC, "_score");
        } else if (sort.equals("time")) {
            pageable = PageRequest.of(page, size, Sort.Direction.DESC, "deadline", "_score");
        } else {
            pageable = PageRequest.of(page, size, Sort.Direction.DESC, "results");
        }

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (keyword == null || keyword.equals("")) {
            boolQueryBuilder.should(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", keyword));
        }
        if (code != null && !code.equals("")) {
            boolQueryBuilder.must(QueryBuilders.matchPhrasePrefixQuery("branch", code));
        }
        if (time != null && !time.equals("")) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("origin").lte(time));
            boolQueryBuilder.must(QueryBuilders.rangeQuery("deadline").gte(time));
        }

        return projectRepository.search(boolQueryBuilder, pageable);
    }

    @Override
    public Map<Integer, List<MySQLProject>> getResearcherProjectsByApproval(String approval) {
        MySQLProject project = this.getByApproval(approval);
        List<MySQLProject> projects = this.getResearcherProjects(project.getManager(), project.getInstitute());
        Map<Integer, List<MySQLProject>> researchers = new HashMap<>();
        for (MySQLProject p : projects) {
            List<MySQLProject> tmp = researchers.getOrDefault(p.getOrigin() / 100, new ArrayList<>());
            tmp.add(p);
            researchers.put(p.getOrigin() / 100, tmp);
        }
        return researchers;
    }

    public int getCate(String value) {
        return ResultEnum.getCategory(value);
    }
}
